package com.hls.controller;

import com.hls.domain.Boy;
import com.hls.domain.Result;
import com.hls.repository.BoyRepository;
import com.hls.service.BoyService;
import com.hls.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by huangliusong on 2017/7/19.
 * 查询男生列表
 */
@RestController
public class BoyController {
    @Autowired
    private BoyRepository boyRepository;
    @Autowired
    private BoyService boyService;
    @GetMapping(value = "/boys")
    public List<Boy> boylist(){
        return boyRepository.findAll();
    }

    @PostMapping(value="/boys")
    public Result<Boy>  boyadd(@Valid Boy boy, BindingResult bindingResult){
        if(bindingResult.hasErrors()){

            return ResultUtil.error(0,bindingResult.getFieldError().getDefaultMessage());
        }
        boy.setAge(boy.getAge());
        boy.setBirth(boy.getBirth());
        boy.setId(1001);
        return ResultUtil.success(boyRepository.save(boy));
    }

    //查询
    @GetMapping(value = "/boys/{id}")
    public Boy findBoy(@PathVariable("id")Integer id){
        return boyRepository.findOne(id);
    }
    //更新
    @PostMapping(value = "/boys/{id}")
    public Boy updateBoy(@PathVariable("id")Integer id,
                         @RequestParam("age")String age,
                         @RequestParam("birth")String birth){
        Boy boy=new Boy();
        boy.setId(id);
        boy.setBirth(birth);
        boy.setAge(age);
        return boyRepository.save(boy);
    }
    //删除
    @DeleteMapping(value = "/boys/{id}")
    public void deleteBoy(@PathVariable("id")Integer id){
        boyRepository.delete(id);
    }

    //通过年龄查询
    @GetMapping(value = "boys/age/{age}")
    public List<Boy> boylistByAge(@PathVariable("age") String age){
        return boyRepository.findByAge(age);
    }

    @PostMapping(value = "/boys/two")
    public void boyTwo(){
        boyService.insertBoyTow();
    }

    /**
     * 对年龄进行判断
     */
    @GetMapping(value = "/boys/getAge/{id}")
    public void  getAge(@PathVariable("id")Integer id)throws Exception{
        boyService.getAge(id);
    }
}
